package com.zfl;

import java.util.Comparator;
import java.util.PriorityQueue;

public class MergeKLists {

    public ListNode mergeKLists(ListNode[] lists) {
        if (lists==null||lists.length==0)
            return null;

        PriorityQueue<ListNode> priorityQueue = new PriorityQueue<>(Comparator.comparingInt(node -> node.val));


        for (ListNode node : lists) {
            if (node!=null) {
                priorityQueue.offer(node);
            }
        }

        ListNode dummy = new ListNode();
        ListNode current  = dummy;

        while(!priorityQueue.isEmpty()) {
            ListNode node = priorityQueue.poll();
            current.next = node;
            current = current.next;
            if (node.next!=null) {
                priorityQueue.offer(node.next);
            }
        }

        return dummy.next;
    }
}
